package com.oe.ldmrabbitmq.service;

import com.oe.ldmrabbitmq.dao.OrderDao;
import com.oe.ldmrabbitmq.dao.PayDetailDao;
import com.oe.ldmrabbitmq.enums.EnumOrderStatus;
import com.oe.ldmrabbitmq.enums.EnumPayStatus;
import com.oe.ldmrabbitmq.pojo.OrderPojo;
import com.oe.ldmrabbitmq.pojo.PayDetailPojo;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class OrderService {

    @Autowired
    AmqpTemplate amqpTemplate;

    @Autowired
    OrderDao orderDao;

    @Autowired
    PayDetailDao payDetailDao;

    public String  createOrder(BigDecimal payAmt){
        OrderPojo pojo=new OrderPojo();
        pojo.setPayAmt(payAmt);
        pojo.setStatus(EnumOrderStatus.TO_BE_PAID);
        String orderId = orderDao.insert(pojo);
        /**
         * 将订单ID发送至 TTL队列
         */
        amqpTemplate.convertAndSend("ex.order.ttl-waiting","order.ttl",orderId);
        return  orderId;
    }

    public String pay(String orderId) {
        String retMsg="支付成功！";
        OrderPojo orderPojo = orderDao.queryOrderById(orderId);
        EnumOrderStatus status = orderPojo.getStatus();
        if(status==EnumOrderStatus.TO_BE_PAID){
            orderDao.updateStatusById(orderId,EnumOrderStatus.HAD_PAID);
            PayDetailPojo pojo=new PayDetailPojo();
            pojo.setOrderId(orderId);
            pojo.setPayAmt(orderPojo.getPayAmt());
            pojo.setStatus(EnumPayStatus.SUCCESS);
            payDetailDao.insert(pojo);
        }else {
            retMsg= "订单未处于待支付状态，请勿重复支付！";
        }
        return retMsg;

    }
    public void expired(String orderId){
        OrderPojo orderPojo = orderDao.queryOrderById(orderId);
        EnumOrderStatus status = orderPojo.getStatus();
        if(status==EnumOrderStatus.TO_BE_PAID){
            orderDao.updateStatusById(orderId,EnumOrderStatus.EXPIRED_NOT_PAID);
        }
    }

    public String cancelOrder(String orderId) {
        String retMsg="取消成功！";
        OrderPojo orderPojo = orderDao.queryOrderById(orderId);
        EnumOrderStatus status = orderPojo.getStatus();
        if(status==EnumOrderStatus.TO_BE_PAID){
            orderDao.updateStatusById(orderId,EnumOrderStatus.CANCEL);
        }else {
            retMsg="订单未处于待支付状态，请勿重复取消！";
        }
        return retMsg;
    }
}
